package com.huatai.exchange.bootup.controller;

import com.alibaba.fastjson.JSON;
import com.faneui.bootup.controller.AbstractRestController;
import com.faneui.common.bean.BaseResp;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.BeanMapper;
import com.faneui.common.utils.DateFormatUtils;
import com.faneui.common.utils.ListUtils;
import com.google.common.collect.Maps;
import com.huatai.exchange.dal.model.ExcCustDataFile;
import com.huatai.exchange.dal.model.ExcExchangeDataFile;
import com.huatai.exchange.facade.CommunicationConstants;
import com.huatai.exchange.facade.CustDataFileController;
import com.huatai.exchange.facade.bean.CustDataFileVo;
import com.huatai.exchange.facade.bean.ExchangeDateFileVo;
import com.huatai.exchange.facade.bean.QueryCustDataFileVoListResp;
import com.huatai.exchange.service.ExcCustDataFileService;
import com.huatai.exchange.service.ExcExchangeDataFileService;
import com.huatai.exchange.service.ExcuteExchangeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "custdatafile")
@Api("客户数据文件配置")
public class CustDataFileControllerImpl extends AbstractRestController implements CustDataFileController {

    @Autowired
    private ExcCustDataFileService excCustDataFileService;

    @Autowired
    private ExcExchangeDataFileService excExchangeDataFileService;

    @Autowired
    private ExcuteExchangeService excuteExchangeService;

    @ApiOperation("列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public QueryCustDataFileVoListResp queryCustDataFileVoList(@ModelAttribute CustDataFileVo custDataFileVo) throws Exception {
        QueryCustDataFileVoListResp resp = new QueryCustDataFileVoListResp();
        try {
            ExcCustDataFile param = BeanMapper.map(custDataFileVo, ExcCustDataFile.class);
            List<ExcCustDataFile> dataFiles = excCustDataFileService.queryExcCustDataFileList(param);
            if (ListUtils.isNotEmpty(dataFiles)) {
                List<CustDataFileVo> vos = BeanMapper.mapList(dataFiles, CustDataFileVo.class);
                resp.setCustDataFileVos(vos);
            }
        } catch (Exception ex) {
            logger.error("", ex);
            resp.setSuccess(false);
            resp.setMsg(ex.getMessage());
        }
        return resp;
    }

    @ApiOperation("执行")
    @RequestMapping(value = "/{custDataFileId}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResp executeCustDataFileExchange(@PathVariable String custDataFileId
            , @RequestParam(required = false,defaultValue = "0") Boolean isTest
            , @RequestParam(required = false,defaultValue = "ht_clear@ehuatai.com") String testAddress
            , @RequestParam(required = false) String occurDate
            , @RequestParam(required = false) String systemCode
            , @RequestParam(required = false) String businId) throws Exception {
        BaseResp resp = new BaseResp();
        if (StringUtils.isBlank(occurDate)) {
            occurDate = DateFormatUtils.yyyyMMdd.format(new Date());
        }
        try {
            logger.info("执行开始，参数：custDataFileId[" + custDataFileId +"],occurDate["+occurDate+"],systemCode["+systemCode+"],businId["+businId+"]");
            ExcCustDataFile custDataFile = excCustDataFileService.queryExcCustDataFile(custDataFileId);
            String jsonProperties = custDataFile.getJsonProperties();

            Map<String, Object> resvMap = StringUtils.isBlank(jsonProperties) ? Maps.newHashMap() : JSON.parseObject(jsonProperties, HashMap.class);
            // 必填 地址
            // 测试入口 将地址变更为 测试地址 ，删除其他地址
            if (isTest != null && isTest) {
                if(custDataFile.getDestAddress().contains("@")) {
                    custDataFile.setDestAddress(testAddress);
                    resvMap.remove(CommunicationConstants.MAIL_toCcMails);
                    resvMap.remove(CommunicationConstants.MAIL_toSeCcMails);
                }else {
                    custDataFile.setDestAddress(custDataFile.getDestAddress().replace("send","test"));
                }
            }
            resvMap.put(CommunicationConstants.communication_dest, custDataFile);

            if(StringUtils.isNotBlank(businId))
                resvMap.put("businId",businId) ;
            excuteExchangeService.executeExchangeDataFile(custDataFile , occurDate, resvMap);

        } catch (Exception ex) {
            logger.error("", ex);
            resp.setSuccess(false);
            resp.setMsg(ex.getMessage());
        }
        return resp;
    }

    @ApiOperation("修改")
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    @ResponseBody
    public BaseResp modifyCustDataFileVo(@RequestBody CustDataFileVo custDataFileVo) throws Exception {
        BaseResp resp = new BaseResp();
        try {
            ExcCustDataFile excCustDataFile = BeanMapper.map(custDataFileVo, ExcCustDataFile.class);
            if (StringUtils.isBlank(excCustDataFile.getDestAddress())) {
                throw new BusinessException("目标邮件或地址不能为空");
            }
            excCustDataFileService.modifyCustDataFile(excCustDataFile);

        } catch (Exception ex) {
            logger.error("", ex);
            resp.setSuccess(false);
            resp.setMsg(ex.getMessage());
        }
        return resp;
    }

    @ApiOperation("增加文件")
    @RequestMapping(value = "/datafile/add", method = RequestMethod.POST)
    @ResponseBody
    public BaseResp addExchangeDataFile(@RequestBody ExchangeDateFileVo vo) throws Exception {
        BaseResp resp = new BaseResp();
        try {
            ExcExchangeDataFile dataFile = new ExcExchangeDataFile();
            dataFile.setCustDataFileId(vo.getCustDataFileId());
            dataFile.setDataFileId(vo.getDataFileId());
            excExchangeDataFileService.addExcExchangeDateFile(dataFile);
        } catch (Exception ex) {
            logger.error("", ex);
            resp.setSuccess(false);
            resp.setMsg(ex.getMessage());
        }
        return resp;
    }

    @ApiOperation("删除文件")
    @RequestMapping(value = "/datafile/delete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResp deleteExchangeFileList(@RequestBody ExchangeDateFileVo vo) throws Exception {
        BaseResp resp = new BaseResp();
        try {
            if(StringUtils.isBlank(vo.getId())) {
                ExcExchangeDataFile dataFile = new ExcExchangeDataFile();
                dataFile.setCustDataFileId(vo.getCustDataFileId());
                dataFile.setDataFileId(vo.getDataFileId());
                List<ExcExchangeDataFile> es = excExchangeDataFileService.queryExcExchangeDateFileList(dataFile) ;
                if(ListUtils.isEmpty(es)) {
                    throw new BusinessException("") ;
                }
                if(es.size()>1)
                    throw new BusinessException("") ;
                excExchangeDataFileService.deleteExcExchangeDateFile(es.get(0).getId());
            } else {
                excExchangeDataFileService.deleteExcExchangeDateFile(vo.getId());
            }
        } catch (Exception ex) {
            logger.error("", ex);
            resp.setSuccess(false);
            resp.setMsg(ex.getMessage());
        }
        return resp;
    }

}
